<script setup lang="tsx">
import { ref, reactive } from "vue";
import {
  ApiSysCgTempletOut,
  ApiSysCgTempletQuery,
  SyscgconfigApi,
  SyscgtempletApi,
} from "@/api-services";
import { feature, getAPI } from "@/axios-utils";
import {
  fetchTableQuery,
  useNetoTable,
  useTableOperate,
  useTableScroll,
} from "@/hooks/common/neto-table";
import { $t } from "@/locales";
import { queryDone } from "@/utils/api";
import syscgtemplet from "./modules/syscgtemplet-modal.vue";
import Search from "./modules/search.vue";
import { ElButton, ElPopconfirm } from "element-plus";

const { tableWrapperRef, scrollConfig } = useTableScroll();

const apiFunc = (params: ApiSysCgTempletQuery) =>
  fetchTableQuery<ApiSysCgTempletQuery, ApiSysCgTempletOut>(
    params,
    (internalParams: ApiSysCgTempletQuery) =>
      getAPI(SyscgtempletApi).getList(internalParams),
  );
const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams,
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: undefined,
    startDate: undefined,
    endDate: undefined,
    cgConfigId: undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: "id",
      //dataIndex: "id",
      label: "编号",
      minWidth: 150,
    },
    {
      prop: "configName",
      //dataIndex: "configName",
      label: "配置名称",
      align: "center",
      minWidth: 200,
    },
    {
      prop: "templateName",
      //dataIndex: "templateName",
      label: "模板名称",
      align: "left",
      minWidth: 200,
    },
    {
      prop: "outFileName",
      //dataIndex: "outFileName",
      label: "输出文件名",
      align: "left",
      minWidth: 300,
    },
    {
      prop: "saveRelativeDirectory",
      //dataIndex: "saveRelativeDirectory",
      label: "保存相对目录",
      align: "left",
      minWidth: 300
    },
    // {
    //   prop:"templateContent",
    //   //dataIndex: "templateContent",
    //   label:"模板内容",
    //   align: "center",
    //   minminWidth: 100,
    // },
    {
      prop: "index",
      label: "操作",
      align: "center",
      fixed: "right",
      minWidth: 270,
      formatter: record => {
        return (
          <div class="flex-center gap-8px">
            <ElButton
              type="primary"
              plain
              size="small"
              onClick={() => edit(record.id!)}
            >
              {$t("common.edit")}
            </ElButton>
            <ElButton
              type="primary"
              plain
              size="small"
              onClick={() => handleClone(record.id!)}
            >
              {$t("common.clone")}
            </ElButton>
            <ElPopconfirm
              onConfirm={() => handleDelete(record.id!)}
              title={$t("common.confirmDelete")}
            >
              {{
                reference: () => (
                  <ElButton type="danger" plain size="small">
                    {$t('common.delete')}
                  </ElButton>
                )
              }}
            </ElPopconfirm>
          </div>
        )
      },
    },
  ],
});

const {
  isVisible,
  handleOpen,
  handleClose,
  operateType,
  handleAdd,
  editingData,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
} = useTableOperate(data, getData);

const handleBatchDeleted = async () => {
  if (!checkedRowKeys.value) return;
  const ids = checkedRowKeys.value;
  // 提交请求
  const [err, res] = await feature(getAPI(SyscgtempletApi).batchDelete(ids.join(',')));

  queryDone(err, async () => {
    if (res?.data.succeeded) {
      onBatchDeleted();
    } else {
      window.$message?.error("删除失败");
    }
  });
};

const modalRef = ref();

const handleClone = async (id: number) => {
  // 提交请求
  const [err, res] = await feature(
    getAPI(SyscgtempletApi).clone(id),
  );

  queryDone(err, async () => {
    if (res?.data.succeeded) {
      window.$message?.success("克隆成功");
      getData();
    } else {
      window.$message?.error("克隆失败");
    }
  });
};

async function handleDelete(id: number) {
  // request
  if (process.env.NODE_ENV === "development")
    console.log(id);

  // 提交请求
  const [err, res] = await feature(getAPI(SyscgtempletApi)._delete(id));

  queryDone(err, async () => {
    if (res?.data.succeeded) {
      onDeleted();
    } else {
      window.$message?.error("删除失败");
    }
  });
}

function edit(id: number) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.codeGenerator.sysCgTemplet.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <syscgtemplet ref="modalRef" v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @close="handleClose" @success="getData" @submitted="getData" />
    </ElCard>
  </div>
</template>

<style scoped></style>
